package com.cennavi.minemapexdemo.activity.exlayer;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.ClusterLayer;
import com.minedata.minemap.overlay.ClusterLayerOptions;
import com.minedata.minemap.overlay.Icon;
import com.minedata.minemap.overlay.MarkerLayerOptions;
import com.cennavi.minemapexdemo.R;
import com.minedata.minemap.overlay.OverlayFeature;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//聚合点图层Demo
public class ClusterActivity extends AppCompatActivity {
    private MapView mapView;
    private static MineMap mineMap;
    private ClusterLayer clusterLayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MinemapAccountManager.getInstance(getApplicationContext(),
                "e2555a3f67ed45d489d63c75457e3d17",
                null,
                "3536");

        setContentView(R.layout.activity_main_layer);
        mapView = findViewById(R.id.mapView);
        mapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @Override
            public void onMapReady(final MineMap mineMap) {
                ClusterActivity.mineMap = mineMap;
                mineMap.setStyleUrl("http://dev.minedata.cn/service/solu/style/id/3536", new MineMap.OnStyleLoadedListener() {

                    @Override
                    public void onStyleLoaded(String s) {
                        //默认显示路况
                        mineMap.setTrafficShow(true);
                        //60秒刷新一次
                        mineMap.setTrafficRote(60);
                        addClusterGraphics();
                    }
                });
                mineMap.setRepaint(true);
                //不显示指南针
                mineMap.getUiSettings().setCompassEnabled(false);
                //不可以旋转地图
                mineMap.getUiSettings().setRotateGesturesEnabled(false);
                mineMap.setCameraPosition(
                        new CameraPosition.Builder()
                                .target(new LatLng(34.2419937, 108.9418989))//设置相机指向的位置
                                .zoom(4)//设置相机缩放等级
                                .tilt(0)//设置相机的俯视角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .build());
                //设置是否显示地图调试信息，默认是不显示
                mineMap.setDebugActive(false);

                MineMap.OnMapClickListener mapClickListener = new MineMap.OnMapClickListener() {
                    @Override
                    public void onMapClick(@NonNull LatLng point) {
                        PointF pointF = mineMap.getProjection().toScreenLocation(point);
                        List<OverlayFeature> list = mineMap.queryRenderedFeatures(pointF, "clusterlayer1", "clusterlayer2");
                        if (list.size() > 0) {
                            List<OverlayFeature> features = clusterLayer.getClusterChildren(list.get(0));
                            if (features.size() > 0) {
                                for (int i = 0; i < features.size(); i++) {
                                    try {
                                        String feature = features.get(i).toJson();
                                        Log.d("cluster", "Feature Json:" + feature);
                                    } catch (Throwable e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                };

                mineMap.addOnMapClickListener(mapClickListener);
            }
        });
    }

    //添加聚合点图层
    public void addClusterGraphics() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.minemap_mylocation_icon_default);
        String bitmapName = "cluster_icon";
        mineMap.addImage(bitmapName, bitmap);
        Map<Integer, String> icons = new HashMap<>();
        icons.put(0, bitmapName);

        ClusterLayerOptions options =
                new ClusterLayerOptions(true, "clusterlayer1", "clusterlayer2");
        options.setClusterRadius(200);
        options.setClusterTextColor(Color.parseColor("#ffff0000"));
        options.setClusterTextFontSize(14);
        options.setIcons(icons);
        options.setMaxZoom(11);
        options.setMinZoom(3);
        options.addAll(getClusterData(loadJsonFromAsset("exp_city_data.json", ClusterActivity.this)));
        clusterLayer = mineMap.addLayer(options);
    }

    //获取点聚合数据
    public List<MarkerLayerOptions.MarkerItem> getClusterData(String data) {
        if (data.isEmpty()) {
            return null;
        }

        List<MarkerLayerOptions.MarkerItem> items = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(data);
            for (int i = 0; i < array.length(); i++) {
                JSONObject json = new JSONObject(array.get(i).toString());
                String latitude = json.get("latitude").toString();
                String longitude = json.get("longitude").toString();
                LatLng latLng;

                for (int j = 0; j < 4; j++) {
                    if (j == 0) {
                        latLng = new LatLng(Double.valueOf(latitude), Double.valueOf(longitude));
                    } else if (j == 1) {
                        latLng = new LatLng(Double.valueOf(latitude) - 0.5, Double.valueOf(longitude) - 0.5);
                    } else if (j == 2) {
                        latLng = new LatLng(Double.valueOf(latitude) + 1.3, Double.valueOf(longitude) - 1);
                    } else {
                        latLng = new LatLng(Double.valueOf(latitude) - 0.2, Double.valueOf(longitude) + 0.3);
                    }

                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.marker_icon);
                    String bitmapName = "marker_icon";
                    mineMap.addImage(bitmapName, bitmap);
                    Map<Integer, String> icons = new HashMap<>();
                    icons.put(0, bitmapName);
                    MarkerLayerOptions.MarkerItem item = new MarkerLayerOptions.MarkerItem();
                    item.icon(bitmapName);
                    item.position(latLng);
                    item.iconRotate(0.0f);
                    items.add(item);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return items;
    }

    //从Asset文件夹中读取json数据
    private static String loadJsonFromAsset(String filename, Context context) {
        try {
            InputStream is = context.getAssets().open(filename);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            return new String(buffer, "UTF-8");
        } catch (Exception e) {
        }
        return null;
    }

    @Override
    protected void onStart() {
        if (mapView != null) {
            mapView.onStart();
        }
        super.onStart();
    }

    @Override
    protected void onResume() {
        if (mapView != null)
            mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (mapView != null)
            mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onStop() {
        if (mapView != null)
            mapView.onStop();
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (mapView != null)
            mapView.onDestroy();
        super.onDestroy();
    }

    public void btnTest(View view) {
        mineMap.snapshot(new MineMap.OnSnapshotReadyCallback() {
            @Override
            public void onSnapshotReady(Bitmap snapshot) {
                //图片存放路径
                String sdCardDir = "/storage/emulated/0/Android/data/com.minedata.minemap/files/";

                try {
                    File dirFile = new File(sdCardDir);
                    if (!dirFile.exists()) {
                        dirFile.mkdirs();
                    }
                    //创建日期
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    String sdfDate = sdf.format(date);
                    File file = new File(sdCardDir, "snapshot" + "(" + sdfDate + ")" + ".png");
                    FileOutputStream fos = new FileOutputStream(file);
                    snapshot.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
